/*
Copyright 2019 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import $ from 'jQuery';
import { merge } from 'lodash';
import { storiesOf } from '@storybook/react';
import Installer from './Installer';
import InstallerStore from './store';
import longLogoSvg from 'shared/assets/images/sample-logo-long.svg';
import { makeApplication } from 'app/services/applications';
import { makeAgentServers } from 'app/installer/services';
import { app, appWithEula, appWithLicense } from './fixtures';

storiesOf('GravityInstaller', module)
  .add('StepProvider', () => {
    return makeInstaller({
      service: {
        fetchApp: () => $.Deferred().resolve(makeApplication(app))
      }
    });
  })
  .add('StepCapacity', () => {
    const store = new InstallerStore();
    store.setState(stateCapacityOnPrem)

    return makeInstaller({
      store,
      siteId: 'siteId',
      service: {
        fetchClusterDetails: () => $.Deferred(),
        fetchAgentReport: () => $.Deferred(),
        startInstall: () => $.Deferred().reject(new Error('server error')),
        verifyOnPrem: () => $.Deferred().reject(new Error('server error'))
      }
    });
  })
  .add('Loading', () => {
    return makeInstaller({
      service: {
        fetchApp: () => $.Deferred()
      }
    });
  })
  .add('Error', () => {
    return makeInstaller({
      service: {
        fetchApp: () => $.Deferred().reject(new Error("server side error"))
      }
    });
  })
  .add('Eula', () => {
    return makeInstaller({
      service: {
        fetchApp: () => $.Deferred().resolve(makeApplication(appWithEula))
      }
    });
  })
  .add('StepLicense', () => {
    return makeInstaller({
      service: {
        fetchApp: () => $.Deferred().resolve(makeApplication(appWithLicense))
      }
    });
  })
  .add('Long Logo', () => {
    const mulesoftApp = merge({}, app, {
      manifest: {
        logo: longLogoSvg
      }
    })
    return makeInstaller({
      service: {
        fetchApp: () => $.Deferred().resolve(makeApplication(mulesoftApp))
      }
    });
  })

function makeInstaller({ store, service, siteId }) {
  const props = {
    store,
    service,
    match: {
      params: {
        siteId
      }
    }
  }

  return (
    <Installer  {...props} />
  )
}

const stateCapacityOnPrem =
{
  "step": "provision",
  "stepOptions": [
    {
      "value": "license",
      "title": "License"
    },
    {
      "value": "new_app",
      "title": "Provider"
    },
    {
      "value": "provision",
      "title": "Capacity"
    },
    {
      "value": "progress",
      "title": "Installation"
    }
  ],
  "license": null,
  "status": "ready",
  "config": {
    "eulaAgreeText": "I Agree To The Terms",
    "eulaHeaderText": "Welcome to the {0} Installer",
    "eulaContentLabelText": "License Agreement",
    "licenseHeaderText": "Enter your license",
    "licenseOptionTrialText": "Trial without license",
    "licenseOptionText": "With a license",
    "licenseUserHintText": "If you have a license, please insert it here. In the next steps you will select the location of your application and the capacity you need",
    "progressUserHintText": "Your infrastructure is being provisioned and your application is being installed.\n\n Once the installation is complete you will be taken to your infrastructure where you can access your application.",
    "prereqUserHintText": `The cluster name will be used for issuing SSH and HTTP/TLS certificates to securely access the cluster.\n\n For this reason it is recommended to use a fully qualified domain name (FQDN) for the cluster name, e.g. prod.example.com`,
    "provisionUserHintText": "Drag the slider to estimate the number of resources needed for that performance level. You can also add / remove resources after the installation. \n\n Once you click \"Start Installation\" the resources will be provisioned on your infrastructure.",
    "iamPermissionsHelpLink": "https://gravitational.com/gravity/docs/overview/",
  },
  "eulaAccepted": true,
  "app": {
    "id": "gravitational.io/everything/1.0.0",
    "packageId": "gravitational.io/everything:1.0.0",
    "name": "everything",
    "displayName": "everything",
    "version": "1.0.0",
    "repository": "gravitational.io",
    "installUrl": "/web/installer/new/gravitational.io/everything/1.0.0",
    "kind": "Cluster",
    "standaloneInstallerUrl": "/portalapi/v1/apps/gravitational.io/everything/1.0.0/installer",
    "size": "5.06 MB",
    "created": "2019-05-13T23:29:35.365Z",
    "createdText": "13/05/2019 19:29:35",
    "logo": "",
    "config": {},
    "licenseRequired": true,
    "eula": "Generic EULA template\n\nEnd-User License Agreement (\"Agreement\")\n\nLast updated: (add date)\n\nPlease read this End-User License Agreement (\"Agreement\") carefully before clicking the \"I Agree\" button, downloading or using My Application (change this) (\"Application\").\n\nBy clicking the \"I Agree\" button, downloading or using the Application, you are agreeing to be bound by the terms and conditions of this Agreement.\n\nIf you do not agree to the terms of this Agreement, do not click on the \"I Agree\" button and do not download or use the Application.\n\nLicense\n\nMy Company (change this) grants you a revocable, non-exclusive, non-transferable, limited license to download, install and use the Application solely for your personal, non-commercial purposes strictly in accordance with the terms of this Agreement.\n\nRestrictions\n\nYou agree not to, and you will not permit others to:\n\na) license, sell, rent, lease, assign, distribute, transmit, host, outsource, disclose or otherwise commercially exploit the Application or make the Application available to any third party.\n\nThe Restrictions section is for applying certain restrictions on the app usage, e.g. user can't sell app, user can't distribute the app. For the full disclosure section, create your own EULA.\n\nModifications to Application\n\nMy Company (change this) reserves the right to modify, suspend or discontinue, temporarily or permanently, the Application or any service to which it connects, with or without notice and without liability to you.\n\nThe Modifications to Application section is for apps that will be updated or regularly maintained. For the full disclosure section, create your own EULA.\n\nTerm and Termination\n\nThis Agreement shall remain in effect until terminated by you or My Company (change this).\n\nMy Company (change this) may, in its sole discretion, at any time and for any or no reason, suspend or terminate this Agreement with or without prior notice.\n\nThis Agreement will terminate immediately, without prior notice from My Company (change this), in the event that you fail to comply with any provision of this Agreement. You may also terminate this Agreement by deleting the Application and all copies thereof from your mobile device or from your desktop.\n\nUpon termination of this Agreement, you shall cease all use of the Application and delete all copies of the Application from your mobile device or from your desktop.\n\nSeverability\n\nIf any provision of this Agreement is held to be unenforceable or invalid, such provision will be changed and interpreted to accomplish the objectives of such provision to the greatest extent possible under applicable law and the remaining provisions will continue in full force and effect.\n\nAmendments to this Agreement\n\nMy Company (change this) reserves the right, at its sole discretion, to modify or replace this Agreement at any time. If a revision is material we will provide at least 30 (changes this) days' notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion.\n\nContact Information\n\nIf you have any questions about this Agreement, please contact us.\n",
    "nodeProfiles": [
      {
        "ram": "2.0GB",
        "name": "basic-node",
        "cpuCount": 1,
        "description": "Basic node",
        "requirementsText": "RAM: 2.0GB, CPU: Core x 1"
      },
      {
        "ram": "8.0GB",
        "name": "high-perf-node",
        "cpuCount": 4,
        "description": "High performance node",
        "requirementsText": "RAM: 8.0GB, CPU: Core x 4"
      },
      {
        "ram": "16GB",
        "name": "ultra-perf-node",
        "cpuCount": 8,
        "description": "Ultra performance node",
        "requirementsText": "RAM: 16GB, CPU: Core x 8"
      }
    ]
  },
  "operation": {
    "id": "5ae8e911-5a4e-4217-b4f3-ec5f316939ad",
    "siteId": "test-on-prem",
    "created": "2019-05-14T21:28:05.446Z",
    "updated": "2019-05-14T21:28:05.446Z",
    "state": "install_initiated",
    "type": "operation_install",
    "provisioner": "onprem",
    "installExpand": {
      "profiles": {
        "basic-node": {
          "description": "Basic node",
          "labels": {
            "gravitational.io/k8s-role": "",
            "role": "basic-node"
          },
          "service_role": "",
          "request": {
            "instance_type": "",
            "count": 0
          }
        },
        "high-perf-node": {
          "description": "High performance node",
          "labels": {
            "gravitational.io/k8s-role": "",
            "role": "high-perf-node"
          },
          "service_role": "",
          "request": {
            "instance_type": "",
            "count": 0
          }
        },
        "ultra-perf-node": {
          "description": "Ultra performance node",
          "labels": {
            "gravitational.io/k8s-role": "",
            "role": "ultra-perf-node"
          },
          "service_role": "",
          "request": {
            "instance_type": "",
            "count": 0
          }
        }
      },
      "servers": null,
      "agents": {
        "basic-node": {
          "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/basic-node\" | sudo bash\n",
          "agent_url": "agent://v6.gravitational.io:32009/basic-node?access_token=30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da",
          "token": "30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da"
        },
        "high-perf-node": {
          "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/high-perf-node\" | sudo bash\n",
          "agent_url": "agent://v6.gravitational.io:32009/high-perf-node?access_token=30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da",
          "token": "30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da"
        },
        "ultra-perf-node": {
          "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/ultra-perf-node\" | sudo bash\n",
          "agent_url": "agent://v6.gravitational.io:32009/ultra-perf-node?access_token=30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da",
          "token": "30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da"
        }
      },
      "subnets": {
        "overlay": "100.96.0.0/16",
        "service": "100.100.0.0/16"
      },
      "vars": {
        "system": {
          "cluster_name": "test-on-prem",
          "ops_url": "https://v6.gravitational.io:32009/t",
          "devmode": false,
          "token": "30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da",
          "teleport_proxy_address": "",
          "docker": {}
        },
        "onprem": {
          "pod_cidr": "100.96.0.0/16",
          "service_cidr": "100.100.0.0/16",
          "vxlan_port": 0
        },
      },
      "package": {
        "repository": "gravitational.io",
        "name": "everything",
        "version": "1.0.0"
      }
    },
    "details": {
      "profiles": {
        "basic-node": {
          "description": "Basic node",
          "labels": {
            "gravitational.io/k8s-role": "",
            "role": "basic-node"
          },
          "service_role": "",
          "request": {
            "instance_type": "",
            "count": 0
          }
        },
        "high-perf-node": {
          "description": "High performance node",
          "labels": {
            "gravitational.io/k8s-role": "",
            "role": "high-perf-node"
          },
          "service_role": "",
          "request": {
            "instance_type": "",
            "count": 0
          }
        },
        "ultra-perf-node": {
          "description": "Ultra performance node",
          "labels": {
            "gravitational.io/k8s-role": "",
            "role": "ultra-perf-node"
          },
          "service_role": "",
          "request": {
            "instance_type": "",
            "count": 0
          }
        }
      },
      "servers": null,
      "agents": {
        "basic-node": {
          "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/basic-node\" | sudo bash\n",
          "agent_url": "agent://v6.gravitational.io:32009/basic-node?access_token=30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da",
          "token": "30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da"
        },
        "high-perf-node": {
          "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/high-perf-node\" | sudo bash\n",
          "agent_url": "agent://v6.gravitational.io:32009/high-perf-node?access_token=30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da",
          "token": "30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da"
        },
        "ultra-perf-node": {
          "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/ultra-perf-node\" | sudo bash\n",
          "agent_url": "agent://v6.gravitational.io:32009/ultra-perf-node?access_token=30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da",
          "token": "30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da"
        }
      },
      "subnets": {
        "overlay": "100.96.0.0/16",
        "service": "100.100.0.0/16"
      },
      "vars": {
        "system": {
          "cluster_name": "test-on-prem",
          "ops_url": "https://v6.gravitational.io:32009/t",
          "devmode": false,
          "token": "30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da",
          "teleport_proxy_address": "",
          "docker": {}
        },
        "onprem": {
          "pod_cidr": "100.96.0.0/16",
          "service_cidr": "100.100.0.0/16",
          "vxlan_port": 0
        },
      },
      "package": {
        "repository": "gravitational.io",
        "name": "everything",
        "version": "1.0.0"
      }
    }
  },
  "tags": {},
  "selectedProvider": null,
  "clusterName": "",
  "onprem": {
    "serviceSubnet": "100.100.0.0/16",
    "podSubnet": "100.96.0.0/16"
  },
  "flavors": {
    "options": [
      {
        "name": "basic",
        "isDefault": false,
        "title": "Basic",
        "profiles": [
          {
            "description": "Basic node",
            "requirementsText": "RAM: 2.0GB, CPU: Core x 1",
            "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/basic-node\" | sudo bash\n",
            "name": "basic-node",
            "instanceTypes": [],
            "instanceTypeFixed": null,
            "count": 1
          }
        ]
      },
      {
        "name": "high-perf",
        "isDefault": true,
        "title": "High performance",
        "profiles": [
          {
            "description": "Basic node",
            "requirementsText": "RAM: 2.0GB, CPU: Core x 1",
            "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/high-perf-node\" | sudo bash\n",
            "name": "high-perf-node",
            "instanceTypes": [],
            "instanceTypeFixed": null,
            "count": 2
          },
          {
            "description": "Complicated node",
            "requirementsText": "RAM: 900.0GB, CPU: Core x 231",
            "instructions": "\ncurl -s --tlsv1.2 -0  \"https://v6.gravitational.io:32009/t/30ac9f0b7f9696e22b62fa0ed518ec5de6c75d222079de6fe95b7dfbe055d0da/high-perf-node\" | sudo bash\n",
            "name": "low-perf-node",
            "instanceTypes": [],
            "instanceTypeFixed": null,
            "count": 6
          }
        ]
      }
    ],
    "prompt": "Please select performance profile"
  },
  agentServers: makeAgentServers({
    "message": "servers [node-1] are up, waiting for -1 more",
    "servers": [{
      "hostname": "node-1",
      "interfaces": {
        "eth0": {
          "ipv4_addr": "192.168.121.69",
          "name": "eth0"
        },
        "eth1": {
          "ipv4_addr": "172.28.128.101",
          "name": "eth1"
        },
        "eth2": {
          "ipv4_addr": "172.29.128.101",
          "name": "eth2"
        }
      },
      "devices": [{
        "name": "/dev/vda1",
        "type": "part",
        "size_mb": 1
      }],
      "role": "high-perf-node",
      "os": {
        "name": "centos",
        "like": ["rhel", "fedora"],
        "version": "7.4.1708"
      },
      "mounts": [
        {
          name: "tmp",
          source: "/"
        },
        {
          name: "docker-root",
          source: "/"
        }
      ]
    },
    {
      "hostname": "node-1-with-a-long-name",
      "interfaces": {
        "eth0": {
          "ipv4_addr": "192.168.121.69",
          "name": "eth0"
        },
        "eth1": {
          "ipv4_addr": "172.28.128.101",
          "name": "eth1"
        },
        "eth2": {
          "ipv4_addr": "172.29.128.101",
          "name": "eth2"
        }
      },
      "devices": [{
        "name": "/dev/vda1",
        "type": "part",
        "size_mb": 1
      }],
      "role": "low-perf-node",
      "os": {
      },
      "mounts": []
    },
    {
      "hostname": "node-3-with-a-long-name",
      "interfaces": {
        "eth0": {
          "ipv4_addr": "192.168.121.69",
          "name": "eth0"
        },
        "eth1": {
          "ipv4_addr": "172.28.128.101",
          "name": "eth1"
        },
        "eth2": {
          "ipv4_addr": "172.29.128.101",
          "name": "eth2"
        }
      },
      "devices": [{
        "name": "/dev/vda1",
        "type": "part",
        "size_mb": 1
      }],
      "role": "low-perf-node",
      "os": {
      },
      "mounts": []
    }
    ]
  }
  ),
}
